package cn.cellcom.agent.util;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONObject;

public class JuheUtil {

	private static Logger log = LoggerFactory.getLogger(JuheUtil.class);

	private static String juheIpUrl = "http://apis.juhe.cn/ip/ip2addr?ip=";
	private static String juheIpKey = "5849bab04b40f2208fce7ced1a2f17a8";

	public static boolean isIP(String addr) {
		if (addr.length() < 7 || addr.length() > 15 || "".equals(addr)) {
			return false;
		}
		String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
				+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
		return addr.matches(regex);
	}

	/**
	 * 获取ip归属地，先查询redis，不存在再查询聚合
	 * 
	 * @param ip
	 * @return
	 */
	public static Belong ipBelong(String ip) {
		Belong bl0 = null;
		try {
			bl0 = RedisManager.getInstance().getBelong().getObject(ip, Belong.class);
		} catch (Exception e) {
			log.error("", e);
		}
		if (bl0 != null) {
			return bl0;
		}

		Belong bl = new Belong();
		bl.setCity("未知");
		bl.setProvince("未知");

		if (!isIP(ip)) {
			return bl;
		}
		String url = juheIpUrl + ip + "&key=" + juheIpKey;
		HttpClient client = null;
		try {
			if (url.startsWith("https://")) {
				client = new SSLClient();
			} else {
				client = new DefaultHttpClient();
			}
			HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			if (HttpStatus.SC_OK == statusCode) {
				String callback = EntityUtils.toString(response.getEntity());
				JSONObject jsonObj = JSONObject.fromObject(callback);
				String data = jsonObj.getString("result");
				if (data == null) {
					return bl;
				}
				JSONObject jsonObj2 = JSONObject.fromObject(data);
				bl = ProvinceAndCity.diparseProvince(jsonObj2.getString("area"));
				bl.setSp(jsonObj2.getString("location"));
				RedisManager.getInstance().getBelong().putObject(ip, bl);
			} else {
				log.error("[JuheUtil.ipBelong]statusCode={}", statusCode);
			}
		} catch (Exception e) {
			log.error("[JuheUtil.sendCallbackEvent] occur exception", e);
		} finally {
			if (client != null && client.getConnectionManager() != null) {
				client.getConnectionManager().shutdown();
			}
		}
		return bl;
	}
}
